var sdk={};
sdk.utils={};
sdk.stringutils={};
sdk.arrayutils={};
sdk.numberutils={};
sdk.dateutils={};
sdk.cookies={};
sdk.objectutils={};
sdk.jsonutils={};
sdk.errorutils={};

/*将String类型解析为Date类型.    
  parseDate('2006-1-1') return new Date(2006,0,1)    
  parseDate(' 2006-1-1 ') return new Date(2006,0,1)    
  parseDate('2006-1-1 15:14:16') return new Date(2006,0,1,15,14,16)    
  parseDate(' 2006-1-1 15:14:16 ') return new Date(2006,0,1,15,14,16);    
  parseDate('2006-1-1 15:14:16.254') return new Date(2006,0,1,15,14,16,254)    
  parseDate(' 2006-1-1 15:14:16.254 ') return new Date(2006,0,1,15,14,16,254)    
  parseDate('不正确的格式') retrun null    
*/     
sdk.dateutils.parse=function(str){
  if(typeof str == 'string'){      
    var results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) *$/);      
    if(results && results.length>3)      
      return new Date(parseInt(results[1]),parseInt(results[2]) -1,parseInt(results[3]));       
    results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) +(\d{1,2}):(\d{1,2}):(\d{1,2}) *$/);      
    if(results && results.length>6)      
      return new Date(parseInt(results[1]),parseInt(results[2]) -1,parseInt(results[3]),parseInt(results[4]),parseInt(results[5]),parseInt(results[6]));       
    results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) +(\d{1,2}):(\d{1,2}):(\d{1,2})\.(\d{1,9}) *$/);      
    if(results && results.length>7)      
      return new Date(parseInt(results[1]),parseInt(results[2]) -1,parseInt(results[3]),parseInt(results[4]),parseInt(results[5]),parseInt(results[6]),parseInt(results[7]));       
  }      
  return null;      
}      
  

/**
 * realize format prototype method to date,(eg. format="YYYY-MM-dd hh:mm:ss");
 */
sdk.dateutils.format=function(date,format){
  if(!format)
    format="yyyy-MM-dd hh:mm:ss";
  var o={
    "M+":date.getMonth()+1, // month
    "d+":date.getDate(), // day
    "h+":date.getHours(), // hour
    "m+":date.getMinutes(), // minute
    "s+":date.getSeconds(), // second
    "q+":Math.floor((date.getMonth()+3)/3), // quarter
    "S":date.getMilliseconds()
    // millisecond
  }
  if(/(y+)/.test(format)){
    format=format.replace(RegExp.$1,(date.getFullYear()+"").substr(4-RegExp.$1.length));
  }
  for(var k in o){
    if(new RegExp("("+k+")").test(format)){
      format=format.replace(RegExp.$1,RegExp.$1.length==1?o[k]:("00"+o[k]).substr((""+o[k]).length));
    }
  }
  return format;
}

sdk.dateutils.formatDate=function(date,template){
  if(typeof(date)=='date'){
      var result = new Date();
      result.setYear(1900+value.year);
      result.setMonth(date.month);
      result.setDate(date.date);
      if(!template)
        template='Y-m-d hh:mm:ss';
      return result.format(template);
  }
  return '';
}

sdk.dateutils.getElapsed = function(date) {
  return Math.abs((date || new Date()).getTime()-date.getTime());
}

sdk.utils.getJson=function(url,params){
  var result=null;
  $.ajax({
    url:url,
    dataType:'json',
    data:params,
    async:false,
    success:function(res){
      result=res;
    },
    complete:function(xhr,textStatus){
      /*if(xhr.readyState=="4"){
        alert(xhr.responseText);
      }*/
      xhr=null;
    },
    error:function(xhr,textStatus,errorThrown){
      // $("#ajaxMessage").text($(this).text()+" out!")
      alert("ajax error:"+textStatus);
      xhr=null;
    }    
  });
  return result;
}

sdk.utils.ajax=function(url,params){
  var result=null;
  jQuery.ajax({
    url:url,
    cache:false,
    data:params,
    async:false,
    success:function(res){
      result=res;
    },
    complete:function(xhr,textStatus){
      /*if(xhr.readyState=="4"){
        alert(xhr.responseText);
      }*/
      xhr=null;
    },
    error:function(xhr,textStatus,errorThrown){
      // $("#ajaxMessage").text($(this).text()+" out!")
      alert("ajax error:"+textStatus);
      xhr=null;
    }    
  });
  return result;
}

/**
 * transfer http params to json object, the params should get by $('#formid').serialize(). 
 * this function support checkbox params submit, eg.: id=1&id=2
 */
sdk.utils.paramToJson=function(param){
  var array=param.split('&');
  var result={};
  for(var i=0;i<array.length;i++){
    var index=sdk.utils.array.indexOf(array[i],'=');
    if(result[array[i].substring(0,index)])
      result[array[i].substring(0,index)]=result[array[i].substring(0,index)]+","+array[i].substring(index+1);
    else
      result[array[i].substring(0,index)]=array[i].substring(index+1);
  }
  return result;
}

sdk.jsonutils.stringify=function(jsonObj){
  return JSON.stringify(jsonObj);
}

sdk.jsonutils.parse=function(jsonStr){
   return eval("("+jsonStr+")");
}

sdk.utils.toJSON=sdk.jsonutils.parse;

sdk.utils.fromJSON=sdk.jsonutils.stringify;

sdk.utils.isArray=function(test){
  if (test!=null&&test.constructor!=String&&(test.constructor==Array||typeof(test.length) == 'number')){
    return true;
  }
  else {
    return false;
  }
}

sdk.utils.isObject=function(test){
  return test!=null&&typeof(test)=='object'&&(test.constructor!=Array);
}

sdk.stringutils.equalsIgnoreCase=function(s1,s2){
	if(s1==s2) return true;
	if(s1==null||s2==null)return false;
	if(typeof(s1)!=typeof(s2)) return false;
	if(typeof(s1)!='string')return false;
	return s1.toUpperCase()==s2.toUpperCase();
}

sdk.stringutils.indexOf=function(str,find,isIgnoreCase){
	checkArgs(arguments,[String,String,Boolean]);
	var mm = (isIgnoreCase)?"i":"";
	var re = eval("/"+ find +"/"+mm);
	var rt = str.match(re);
	return (rt == null) ? -1:rt.index; 
}

sdk.utils.println=function (v){
	if(!v||typeof(v)=='string'&&v.charAt(0)=='!')
		errprintln(v);
	else
		document.write(v+'<br>');
}


sdk.errorutils.writeln=function (v){
	document.write('<font color=red>'+v+'</font>'+'<br>');
}

sdk.utils.println=function(){
  if(console) console.log(arguments);
}

sdk.errorutils.handle=function(e){
  var errormsg=sdk.errorutils.getExceptionStack(e);
  sdk.utils.println(errormsg);
  alert(errormsg);
}

sdk.errorutils.getExceptionStack=function(e){
  var result=e.name+": "+e.message;
  if(e.stack)
    result+="\n"+e.stack;
  return result;  
}

sdk.utils.assertEquals=function(){
	try{
		if(arguments.length==0) return println('!argument is empty');
		if(arguments.length==1) return println(arguments[0]);
		if(arguments.length==3) return println('!arguments is nore then 2');
		if(arguments.length==2){
			var v=arguments[0]===arguments[1];
			if(v)
				println(v) //return println(arguments[0]+' is '+arguments[1]);
			else
				errprintln(arguments[0] +' isn\'t '+arguments[1]);
		}
	}
	catch(e){
		errprintln("catch a error:"+e);
	}
}
var assertEquals=sdk.utils.assertEquals;

sdk.utils.isBlank=function(v){
	var result=(v==undefined||v==null||v==0||v=='');
	if(!result&&isArray(v))
		result=v.length==0;
	return result;
}

sdk.utils.isValid=function(v){
  return !sdk.utils.isBlank(v);
};

sdk.utils.isIE=function() {
  if(document.all) return true;
  return false;
}

sdk.utils.isTime=function (str){//1 短時間，形如 (13:04:06)
	var a = str.match(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})$/);
	if (a == null) {
		//alert('輸入的參數不是時間格式');
		return false;}
	if (a[1]>=24 || a[3]>=60 || a[4]>=60){
		//alert("時間格式不對");
		return false
	}
	return true;
}

sdk.utils.isDate=function(str){//2. 短日期，形如 (2008-07-22)
	var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/); 
	if(r==null)return false; 
	var d= new Date(r[1], r[3]-1, r[4]); 
	return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]);
}

sdk.utils.isDateTime=function(str){//3 長時間，形如 (2008-07-22 13:04:06)
	var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2})[:\.](\d{1,2})[:\.](\d{1,2})$/; 
	var r = str.match(reg); 
	if(r==null)return false; 
	var d= new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]); 
	return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]);
}

sdk.utils.isNumber=function(val){
	return isFloat(val);
}
	
sdk.utils.isFloat=function(val){
	var pattern=/^(-)?[0-9]{1,20}(\.)?[0-9]{0,20}$/;   //校驗是否全由數字組成,包括負數
	return pattern.test(val);
}

sdk.utils.isInt=function(val){
	var pattern=/^(-)?[0-9]{1,20}$/;   //校驗是否全由數字組成
	return pattern.test(val);
}

sdk.utils.isTrue=function(val){
  if(val==NaN||val==undefined||val==null) return false;
  return val==true||val>0||val=='true'||val=='1';
}

sdk.stringutils.format=function(template){
  var args = Array.prototype.slice.call(arguments, 1);
	return template.replace(/\{(\d+)\}/g, function(m,i){
  	return args[i];
  });
}

sdk.stringutils.concat=function(){
  var result='';
  for(var item in arguments){
    result+=item;
  }
  return result;
};

/**
 *alert(sdk.stringutils.template("abc{0}efg{1}","d","h"));
 *alert(sdk.stringutils.template("the name is:${name}, the age is ${age}",{name:'张三',age:23}));
 * 
 */
sdk.stringutils.template=function(str,arg1,arg2,arg3){ 
  var result;
  if(typeof(arg1)=='object'){
    result=str.replace(/\$\{(\w+)\}/g,function(){
      return arg1[arguments[1]];
    });
  }
  else{
    var args=arguments;
    result=str.replace(/\{(\d*)\}/g,function(group){
      return args[parseInt(arguments[1])+1];
    });
  }
  return result;
};

/**
 * 其实replace是可以实现全部替换的,关键是正则表达式最后的g (eg. alert("a-b-c-defg".replace(/-/g,"."));  )
 */
sdk.stringutils.replaceAll=function(str,find,repl){
  var index=0;
  while(str.indexOf(find,index)>=0){
    str=str.replace(find,repl);
    index=str.indexOf(find,index);
  }
  return str;
}

/**
 *alert(stringutils.format("abc{0}efg{1}","d","h"));
 *alert(stringutils.format("the name is:${name}, the age is ${age}",{name:'张三',age:23}));
 * 
 */
sdk.stringutils.format=function(str,arg1,arg2,arg3){
  var result;
  if(typeof(arg1)=='object'){
    result=str.replace(/\$\{(\w+)\}/g,function(){
      return arg1[arguments[1]];
    });
  }
  else{
    var args=arguments;
    result=str.replace(/\{(\d*)\}/g,function(group){
      return args[parseInt(arguments[1])+1];
    });
  }
  return result;
};

sdk.stringutils.trim=function(str){
  return str.replace(/^\s+|\s+$/g, '');
}

sdk.arrayutils.indexOf=function(array,obj){
  for(var i=0,len=array.length;i<len;i++){
    if(array[i]==obj)
      return i;
  }
  return -1;
}

sdk.arrayutils.remove=function(array,obj){
	 var index = sdk.utils.array.indexOf(array,obj);
	 if(index != -1){
	     array.splice(index, 1);
	 }
	 return array;
};
sdk.arrayutils.removeAt=function(array,index){
   if(index != -1){
       array.splice(index, 1);
   }
   return array;
};

sdk.arrayutils.getFieldArray=function(array,fieldName){
  var result=[];
  for(var i=0;i<array.length;i++){
    result.push(array[i][fieldName]);
  }
  return result;
}

sdk.arrayutils.getFieldStr=function(array,fieldName,delimiter){
  return sdk.arrayutils.toStr(sdk.arrayutils.getFieldArray(array,fieldName));
}

sdk.arrayutils.toStr=function(array,delimiter){
  var result='';
  delimiter=delimiter||',';
  for(var i=0;i<array.length;i++){
    if(result!='')
      result+=delimiter+array[i];
    else
      result=array[i];
  }
  return result;
}

sdk.numberutils.round=function(num,digit){
	/*if(!digit) digit=2;
	var p=Math.pow(10,digit);
	return Math.round(num*p)/p;*/
	return parseFloat(num.toFixed(digit)); //这个方法是js内置的,更简单方便.
}

//根据QueryString参数名称获取值
sdk.utils.getQueryStringByName=function(name){
	var result = location.search.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
	if (result == null || result.length < 1){
		return "";
	}
	return result[1];
}

sdk.utils.generateSequence=function(){
  if(!window.top.idSeed)
    window.top.idSeed=0;
  window.top.idSeed++;
  return window.top.idSeed;
}

sdk.utils.generateId=function(element,prefix){
    var id=null;
    if(element.id)
     id=element.id;
    else if(element.name){
     if(!document.getElementById(element.name))
      id=element.name;
     else{
      id=element.name+'_'+sdk.utils.generateSequence();
   }
  }else{
   id=(prefix||"gen")+'_'+sdk.utils.generateSequence();
  }
  return id;
}

sdk.objectutils.copyfields=function(srcobj,targetobj,includes){
  targetobj=targetobj||{};
 if(includes.length>0){
   for(var i=0;i<includes.length;i++){
     if(srcobj[includes[i]]!=undefined){
       targetobj[includes[i]]=srcobj[includes[i]];
     }
   }
 }
 else{
   $.extend(targetobj,srcobj);
 }
 return targetobj;
}

sdk.cookies.get=function(name){
  var arrCookie=document.cookie.split("; ");
  for(var i=0;i<arrCookie.length;i++){
    var arr=arrCookie[i].split("=");
    if(name==arr[0]){
      return decodeURIComponent(arr[1]);
    }
  }
  return null;
};

sdk.cookies.set=function(cookieName,cookieValue,dayNum,path,domainValue){
  var expire="";
  path=path||"/";
  if(typeof(cookieValue)=='object')
    cookieValue=encodeURIComponent(jsonutils.fromJSON(cookieValue)).replace(/\(/g,"%28").replace(/\)/g,"%29");
  if(dayNum){
    expire=new Date((new Date()).getTime()+dayNum*86400000);
    expire=";expires="+expire.toGMTString();
  }
  var domain=(domainValue==null)?"":";domain="+domainValue;
  document.cookie=cookieName+"="+cookieValue+expire+";path="+path+domain;
};

sdk.cookies.remove=function(name,path,domain){
  var exp=new Date();
  exp.setTime(exp.getTime()-1000000);
  var cval=getCookie(name);
  path=path||"/";
  domain=(domain==null)?"":";domain="+domain;
  if(cval!=null)
    document.cookie=name+"=;expires="+exp.toGMTString()+";path="+path+domain;
}

var browserName=navigator.userAgent.toLowerCase();
sdk.browser={
  version:(browserName.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,'0'])[1],
  isSafari:/webkit/i.test(browserName)&&!this.chrome,
  isOpera:/opera/i.test(browserName),
  isFirefox:/firefox/i.test(browserName),
  isMsie:/msie/i.test(browserName)&&!/opera/.test(browserName),
  isMozilla:/mozilla/i.test(browserName)&&!/(compatible|webkit)/.test(browserName)&&!this.chrome,
  isChrome:/chrome/i.test(browserName)&&/webkit/i.test(browserName)&&/mozilla/i.test(browserName)
}

/*
 * 中文判断函数，允许生僻字用英文“*”代替 返回true表示是符合条件，返回false表示不符合
 */ 

sdk.utils.isChinese=function(str){
  var badChar="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  badChar+="abcdefghijklmnopqrstuvwxyz";
  badChar+="0123456789";
  badChar+=" "+"　";// 半角与全角空格
  badChar+="`~!@#$%^&()-_=+]\\|:;\"\\'<,>?/";// 不包含*或.的英文符号
  if(""==str){
    return false;
  }
  for(var i=0;i<str.length;i++){
    var c=str.charAt(i);// 字符串str中的字符
    if(badChar.indexOf(c)>-1){
      return false;
    }
    return true;
  }
}
/*
 * 数字判断函数，返回true表示是全部数字，返回false表示不全部是数字
 */ 
sdk.utils.isNumber=function (str){
	if(""==str){ 
	   return false; 
	}
	var reg = /-?\D/; 
	return str.match(reg)==null; 
}

sdk.utils.getDomain=function(url){
  url=url||window.location.href;
  var host="null";
  if(typeof url=="undefined"||null==url)
    url=window.location.href;
  var regex=/.*\:\/\/([^\/]*).*/;
  var match=url.match(regex);
  if(typeof match!="undefined"&&null!=match)
    host=match[1];
  return host;
}

function test(){
	sdk.utils.assertEquals(equalIgnoreCase("abcd",'ABcd'));
	sdk.utils.assertEquals(sdk.stringutils.indexOf("abcd",'A',true),0);
	sdk.utils.assertEquals(indexOf("abcd",'A'),-1);
	sdk.utils.assertEquals(indexOf("abcd",'C',1,true),2);
	sdk.utils.assertEquals(indexOf("abcd",'C',1),-1);
	var mydate=new Date();
	sdk.utils.println('now(yyyy-MM-dd hh:mm:ss)：'+mydate.format('yyyy-MM-dd hh:mm:ss'));
	sdk.utils.println('now(yyyy年MM月dd日hh小時mm分ss秒):'+mydate.format("yyyy年MM月dd日hh小時mm分ss秒"));
	sdk.utils.println('now(default format)：'+mydate.format());
	sdk.utils.assertEquals(isBlank('')&&isBlank(null)&&!isBlank(['a','b'])&&isBlank([]));
	sdk.utils.assertEquals(sdk.arrayutils.isArray(['a','b']));
	sdk.utils.assertEquals(!sdk.arrayutils.isArray('a'));
	sdk.utils.assertEquals(parseInt("10",10),10);
	sdk.utils.assertEquals(parseInt("09"),0);
	sdk.utils.assertEquals(sdk.utils.isTime('13:04:06'));
	sdk.utils.assertEquals(sdk.utils.isDate('2008-07-22'));
	sdk.utils.assertEquals(sdk.utils.isDateTime('2008-07-22 13:04:06'));
	sdk.utils.assertEquals(sdk.utils.isTime('130406'));
	sdk.utils.assertEquals(sdk.utils.isDate('2008/07/22'));
	sdk.utils.assertEquals(sdk.utils.isDateTime('2008/01/22 13.04.59'));
	sdk.utils.assertEquals(sdk.utils.isTime('236006'),false);
	sdk.utils.assertEquals(sdk.utils.isDate('08/07/22'),false);
	sdk.utils.assertEquals(sdk.utils.isDateTime('2008-13-22 13:04:60'),false);
	sdk.utils.assertEquals(sdk.utils.isNumber('-1.23'));
	sdk.utils.assertEquals(sdk.utils.isNumber('31'));
	sdk.utils.assertEquals(sdk.utils.isInt('-1.23'),false);
	sdk.utils.assertEquals(sdk.utils.isInt('-31'));
	sdk.utils.assertEquals(sdk.utils.isValid(1));
	sdk.utils.assertEquals(sdk.stringutils.format("you are {0}, I am {1}",'boss','employee.'),'you are boss, I am employee.');
	sdk.utils.assertEquals(sdk.arrayutils.indexOf(['a','b'],'b'),1);
	sdk.utils.assertEquals(sdk.arrayutils.indexOf(sdk.arrayutils.remove(['a','b'],'a'),'a'),-1);
	sdk.utils.assertEquals(sdk.numberutils.round((1.155+2.2),10),3.355);
	sdk.utils.assertEquals(sdk.numberutils.round((1.155+2.2),2),3.36);
  sdk.utils.assertEquals(sdk.stringutils.format("the name is:${name}, the age is ${age}",{name:'张三',age:23}),"the name is:张三, the age is 23");
  sdk.utils.assertEquals(sdk.stringutils.format("abc{0}efg{1}","d","h"),"abcdefgh");

	sdk.utils.println('end.');
}

